/*
 * Copyright 2010-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.pathlet.core.impl;

import org.pathlet.core.config.ResourceConfig;
import org.pathlet.core.config.def.BeanResourceConfig;
import org.pathlet.core.*;
import org.pathlet.core.exception.ResourceAccessException;
import org.pathlet.core.exception.ResourceException;
import org.pathlet.util.ValueUtils;

import static org.pathlet.core.PathletConstants.CONTAINER_SCOPE;

/**
 *
 * @author Charlie Zhang
 *
 */
public class ConfigBeanResourceFactory implements ConfigResourceFactory<BeanResource> {

	private PathletContainer container;

	private PathPattern pathPattern = MATCH_PATTERN_ALL;

	private String defaultScope = CONTAINER_SCOPE;

	public PathletContainer getContainer() {
		return this.container;
	}

	public void setContainer(PathletContainer container) {
		this.container = container;
	}

	public PathPattern getPathPattern() {
		return this.pathPattern;
	}

	public void setPathPattern(PathPattern pathPattern) {
		this.pathPattern = pathPattern;
	}

	public String getDefaultScope() {
		return defaultScope;
	}

	public void setDefaultScope(String defaultScope) {
		this.defaultScope = defaultScope;
	}

	public BeanResource createResource(ResourceConfig resourceConfig) throws ResourceException {
		try {
			BeanResourceConfig config = (BeanResourceConfig)resourceConfig;

			//Set the default scope if the scope is empty
			if(ValueUtils.isEmpty(config.getScope())) {
				config.setScope(getDefaultScope());
			}

			return new BeanResource(this, config);
		}
		catch(Exception e) {
			throw new ResourceAccessException("Failed to get resource path=" + resourceConfig.getPath(),
					e, resourceConfig.getPath());
		}
	}


}
